# -*- encoding: utf-8 -*-
"""
    base.py
    :description: 
    :date: 2020/09/04 17:15:54
    :version      :1.0
    :copyright: (c) 2020 by enjoyZHou
"""
# from fastapi.encoders import jsonable_encoder

DEFAULT_API_ERROR_CODES = {
    400: u"请求参数/格式错误",
    401: u"当前用户没有登录",
    402: u"付费内容",
    403: u"没有操作权限",
    404: u"资源不存在",
    405: u"不允许调用该方法",
    406: u"不可接受",
    407: u"需要代理身份验证",
    408: u"请求超时，请重试",
    409: u"发生指令冲突",
    426: u"请升级新版本",
    500: u"某个服务器异常，请重试",
    501: u"暂不支持此接口",
    502: u'暂停服务',
    600: u"自定义错误",
}


def json_response(code=0, data=None, message=None, request=None):
    """
    构造api的json返回
    :param code:
    :param data:
    :param message:
    :param request:
    :return:
    """
    rst_dict = dict(code=code)

    err_message = DEFAULT_API_ERROR_CODES.get(code)
    if err_message:
        rst_dict['message'] = err_message

    # 如果传入了, 可能会覆盖默认的
    if message:
        rst_dict['message'] = message

    if data:
        rst_dict['data'] = data
    else:
        rst_dict['data'] = '' if data is None else data

    rst_dict['request'] = request and request.query_params

    return rst_dict
